package com.oracle.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.github.pagehelper.Page;
import com.oracle.Service.impl.UserService;
import com.oracle.entity.ResultBean;
import com.oracle.pojo.User;
import com.oracle.pojo.vo.UserVo;
import com.oracle.util.SendMail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Transactional
    @RequestMapping("/front/update2")
    @ResponseBody
    public ResultBean updateUserInfo2(@Validated User user,String oldpassword,String code1,Errors errors,HttpSession session){
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            String code2 = (String) session.getAttribute("emailCode");
            System.out.println("code1:"+code1+"  code2:"+code2);
            if (code1!=code2&&!code1.equals(code2)){
                return ResultBean.getResultBean(303,"验证码错误",null);
            }else{
                session.removeAttribute("emailCode");
                if (user.getUid()!=null&&user.getUid()!=0){
                    if (userService.findOneByUid(user.getUid()).getPassword()!=oldpassword&&!oldpassword.equals(userService.findOneByUid(user.getUid()).getPassword())){
                        return ResultBean.getResultBean(302,"原密码错误",null);
                    }else{
                        if (errors!=null&&errors.getFieldErrors()!=null&&errors.getFieldErrors().size()>0){
                            for (FieldError fieldError : errors.getFieldErrors()){
                                map.put(fieldError.getField()+"Error",fieldError.getDefaultMessage());
                            }
                            return ResultBean.getResultBean(300,"修改信息有空值",map);
                        }else{
                            Integer code = userService.updateUserInfo(user);
                            if (code>0){
                                return ResultBean.success("修改成功",user);
                            }
                            return ResultBean.getResultBean(301,"没有该用户id",null);
                        }
                    }
                }else {
                    return ResultBean.getResultBean(301,"没有该用户id",null);
                }
            }
        }catch (Exception e){
            return ResultBean.fail("查询失败", null);
        }
    }

    @RequestMapping("/front/update1")
    @ResponseBody
    public ResultBean updateUserInfo(@Validated User user,Errors errors){
        Map<String,Object> map = new HashMap<String,Object>();
        try{
            if (user.getUid()!=null&&user.getUid()!=0){
                if (errors!=null&&errors.getFieldErrors()!=null&&errors.getFieldErrors().size()>0){
                    for (FieldError fieldError : errors.getFieldErrors()){
                        map.put(fieldError.getField()+"Error",fieldError.getDefaultMessage());
                    }
                    return ResultBean.getResultBean(300,"修改信息有空值",map);
                }else{
                    Integer code = userService.updateUserInfo(user);
                    if (code>0){
                        return ResultBean.success("修改成功",user);
                    }
                    return ResultBean.getResultBean(301,"没有该用户id",null);
                }
            }else {
                return ResultBean.getResultBean(301,"没有该用户id",null);
            }
        }catch (Exception e){
            return ResultBean.fail("查询失败", null);
        }
    }


    @RequestMapping("/front/find")
    @ResponseBody
    public ResultBean findUserInfoByUid(Integer uid){
        try{
            if (uid!=null&&uid!=0){
                User user = userService.findOneByUid(uid);
                return ResultBean.success("查询成功", user);
            }
            return ResultBean.getResultBean(300,"没有该用户id",null);
        }catch (Exception e){
            return ResultBean.fail("查询失败", null);
        }
    }



    @RequestMapping("/front/userUpdate")
    @ResponseBody
    public Map<String,Object> userUpdate(@Validated User user,Errors error,String code,HttpServletRequest request){
        Map<String,Object> map =  new HashMap<String,Object>();
        HttpSession session = request.getSession();
        String codeVo = (String) session.getAttribute("emailCode");

        if (!code.equals(codeVo)){
            map.put("result",501);
        }else {
            if (error!=null&&error.getFieldErrors()!=null&&error.getFieldErrors().size()>0){
                map.put("result",401);
                for (FieldError fieldError : error.getFieldErrors()) {
                    map.put(fieldError.getField()+"Error",fieldError.getDefaultMessage());
                }
                map.put("user",user);
            }else{
                String result = userService.addNewUser(user);
                if (result.equals("YES")){
                    map.put("result",200);
                }else{
                    map.put("result",301);
                    map.put("user",user);
                }
            }
        }
        session.removeAttribute("emailCode");

        return map;
    }

    @RequestMapping("/front/email2")
    @ResponseBody
    public Map<String,Object> sendMail2(String email){
        Map<String,Object> map =  new HashMap<String,Object>();
        try{
            // 实例化一个发送邮件的对象
            SendMail mySendMail = new SendMail();
            mySendMail.sendMail(email, "<h2 color='red'>最新的消息！请关注My-BookStore。<h2>");
            map.put("result",200);
            return map;
        }catch (Exception  e){
            map.put("result",300);
            return map;
        }
    }


    @RequestMapping("/front/email")
    @ResponseBody
    public Map<String,Object> sendMail(String email,HttpSession session){
        Map<String,Object> map =  new HashMap<String,Object>();
        try{
            // 实例化一个发送邮件的对象
            SendMail mySendMail = new SendMail();

            String code = UUID.randomUUID().toString().replaceAll("-","").substring(0,4);
            session.setAttribute("emailCode",code);
            // 根据页面获取到的邮箱找到该用户信息
            // 如果查到该用户，并且用户名和页面输入相同验证成功，发送邮件
            mySendMail.sendMail(email, "验证码为，请及时注册：" + code);
            map.put("result",200);
            return map;
        }catch (Exception  e){
            map.put("result",300);
            return map;
        }
    }


    //验证码
    @RequestMapping("/front/captcha")
    public void hutoolCaptcha(HttpServletRequest request, HttpServletResponse response)  {
        try{
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 100);
            request.getSession().setAttribute("code",lineCaptcha.getCode());
            lineCaptcha.write(response.getOutputStream());
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }


    @RequestMapping(value = "/front/return",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> Return(HttpSession session){
        Map<String,Object> map =  new HashMap<String,Object>();
        //退出登录，清除缓存
        if (session.getAttribute("userLogin")!=null){
            session.removeAttribute("userLogin");
            map.put("result",200);
        }
        return map;
    }

    @RequestMapping("/front/userLogin")
    @ResponseBody
    public Map<String,Object> userLogin(User user,String code, Errors errors, HttpSession session){
        Map<String,Object> map =  new HashMap<String,Object>();
        String codeVo = (String) session.getAttribute("code");
        if (user.getUsername()==null||user.getUsername().equals("")){
            map.put("result",401);
            map.put("usernameError","账号不能为空！");
            return map;
        }
        if(user.getPassword()==null||user.getPassword().equals("")){
            map.put("result",401);
            map.put("passwordError","密码不能为空！");
            return map;
        }
        if (codeVo.toLowerCase().equals(code.toLowerCase())){
            session.removeAttribute("code");
            User userVo = userService.SelectUserByUserName(user);
            if (!userVo.getPassword().equals(user.getPassword())){
                map.put("result",301);
                map.put("user",user);
                map.put("LoginError","账号或者密码错误！");
            }else{
                map.put("result",200);
                if (session.getAttribute("noUser")!=null){
                    session.removeAttribute("noUser");
                }
                session.setAttribute("userLogin",userVo);
            }

        }else {
            map.put("result",402);
            map.put("codeError","验证码错误");
        }
        return map;
    }


    @RequestMapping("/userShow")
    public String userShow(@RequestParam(value = "currentPage" ,defaultValue = "1",required = false) Integer currentPage,
                           @RequestParam(value = "pageSize",defaultValue = "3",required = false)  Integer pageSize,
                           UserVo userVo, Model model){
//从数据库中取数据
        //使用分页等
        Integer startPage;
        Integer endPage;
        if (currentPage<1){
            currentPage = 1;
        }
        Page<User> pages = userService.showUsers(currentPage,pageSize,userVo);
        if (currentPage>pages.getPages()){
            pages = userService.showUsers(pages.getPages(),pageSize,userVo);
        }
        if (pages.getPages()<10){
            startPage = 1;
            endPage = pages.getPages();
        }else{
            startPage = pages.getPageNum()-4;
            endPage = pages.getPageNum()+5;
        }
        model.addAttribute("startPage",startPage);
        model.addAttribute("endPage",endPage);

        model.addAttribute("users",pages.getResult());
        model.addAttribute("pageInfo",pages);
        model.addAttribute("userVo",userVo);

        return "/admin/userShow";
    }
}
